import 'package:flutter/material.dart';
import '../model/CartInfoModel.dart';
import 'dart:convert';
import 'package:flustars/flustars.dart';

class ShoppingCartProvide with ChangeNotifier {
  String cartJsonString = "[]";
  List<CartInfoModel> cartInfoList = [];
  double allPrice = 0;
  int allCount = 0;
  bool isAllCheck = true;

  //添加商品信息
  save(goodsId, goodsName, count, price, images) async {
    await SpUtil.getInstance();
    cartJsonString = SpUtil.getString("cartInfo");
    var temp = cartJsonString.isEmpty ? [] : json.decode(cartJsonString.toString());
    List<Map> tempList = (temp as List).cast();
    var isHave = false;
    int index = 0;
    allPrice = 0;
    allCount = 0;
    tempList.forEach((item) {
      if (item['goodsId'] == goodsId) {
        tempList[index]['count'] = item['count'] + 1;
        cartInfoList[index].count++;
        isHave = true;
      }
      if (item['isCheck']) {
        allPrice += (cartInfoList[index].price * cartInfoList[index].count);
        allCount += cartInfoList[index].count;
      }
      index++;
    });
    if (!isHave) {
      Map<String, dynamic> newGoods = {
        'goodsId': goodsId,
        'goodsName': goodsName,
        'count': count,
        'price': price,
        'images': images,
        'isCheck': true,
      };
      tempList.add(newGoods);
      cartInfoList.add(CartInfoModel.fromJson(newGoods));

      allPrice += (count * price);
      allCount += count;
    }
    cartJsonString = json.encode(tempList).toString();
    debugPrint("json数据模型：$cartJsonString");
    debugPrint("model数据模型：$cartInfoList");

    SpUtil.putString("cartInfo", cartJsonString);
    notifyListeners();
  }

  //获取保存的商品信息
  getCartInfo() async {
    await SpUtil.getInstance();
    cartJsonString = SpUtil.getString("cartInfo");
    cartInfoList = []; //获取商品信息前将集合置空，防止数据混乱
    if (cartJsonString.isEmpty) {
      cartInfoList = [];
    } else {
      List<Map> tempList = (json.decode(cartJsonString.toString()) as List).cast();
      allPrice = 0;
      allCount = 0;
      isAllCheck = true;
      tempList.forEach((item) {
        if (item['isCheck']) {
          allPrice += (item['price'] * item['count']);
          allCount += item['count'];
        } else {
          isAllCheck = false;
        }
        cartInfoList.add(new CartInfoModel.fromJson(item));
      });
    }
    notifyListeners();
  }

  //清空数据
  remove() async {
    await SpUtil.getInstance();
    SpUtil.remove("cartInfo");
    cartInfoList = [];
    allCount = 0;
    allPrice = 0;
    debugPrint("购物车数据清空。。。。。");
    notifyListeners();
  }

  //删除单个商品
  deleteOneGoods(String id) async {
    await SpUtil.getInstance();
    cartJsonString = SpUtil.getString("cartInfo");
    List<Map> tempList = (json.decode(cartJsonString.toString()) as List).cast();
    int tempIndex = 0;
    int deleteIndex = 0;
    tempList.forEach((item) {
      if (item['goodsId'] == id) {
        deleteIndex = tempIndex;
      }
      tempIndex++;
    });
    tempList.removeAt(deleteIndex);
    cartJsonString = json.encode(tempList).toString();
    SpUtil.putString("cartInfo", cartJsonString);
    await getCartInfo();
  }

  //改变商品选择状态
  changeCheckState(CartInfoModel item) async {
    await SpUtil.getInstance();
    cartJsonString = SpUtil.getString("cartInfo");
    List<Map> tempList = (json.decode(cartJsonString.toString()) as List).cast();
    int tempIndex = 0;
    int changeIndex = 0;
    tempList.forEach((data) {
      if (data['goodsId'] == item.goodsId) {
        changeIndex = tempIndex;
      }
      tempIndex++;
    });
    tempList[changeIndex] = item.toJson();
    cartJsonString = json.encode(tempList).toString();
    SpUtil.putString("cartInfo", cartJsonString);
    await getCartInfo();
  }

  //点击全选按钮操作
  changeAllBtnState(bool isCheck) async {
    await SpUtil.getInstance();
    cartJsonString = SpUtil.getString("cartInfo");
    List<Map> tempList = (json.decode(cartJsonString.toString()) as List).cast();
    List<Map> newList = [];
    tempList.forEach((item) {
      var newItem = item;
      newItem['isCheck'] = isCheck;
      newList.add(newItem);
    });
    cartJsonString = json.encode(tempList).toString();
    SpUtil.putString("cartInfo", cartJsonString);
    await getCartInfo();
  }

  //商品数量的加减
  addOrReduceAction(var item, String todo) async {
    await SpUtil.getInstance();
    cartJsonString = SpUtil.getString("cartInfo");
    List<Map> tempList = (json.decode(cartJsonString.toString()) as List).cast();
    int tempIndex = 0;
    int changeIndex = 0;
    tempList.forEach((data) {
      if (data['goodsId'] == item.goodsId) {
        changeIndex = tempIndex;
      }
      tempIndex++;
    });
    if (todo == "add") {
      item.count++;
    } else if (item.count > 1) {
      item.count--;
    }
    tempList[changeIndex] = item.toJson();
    cartJsonString = json.encode(tempList).toString();
    SpUtil.putString("cartInfo", cartJsonString);
    await getCartInfo();
  }
}
